package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.adapter.PostAdapter;
import com.example.qu_tao.database.DBHelper;
import com.example.qu_tao.entity.Post;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class QuTaoQuanFragment extends Fragment {

    private TextView tabFollow, tabMine;
    private TextView tabRecommend;
    private RecyclerView recyclerView;
    private FloatingActionButton fab;
    private PostAdapter postAdapter;
    private List<Post> postList = new ArrayList<>();
    // 定义颜色和大小常量
    private final int COLOR_SELECTED = R.color.black;
    private final int COLOR_UNSELECTED = R.color.gray;
    private final float TEXT_SIZE_SELECTED = 18f; // sp
    private final float TEXT_SIZE_UNSELECTED = 16f; // sp
    private BroadcastReceiver updateReceiver;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_qutaoquan, container, false);
        initViews(view);
        setupTabs();
        setupRecyclerView();
        setupFab();
        loadRecommendData(); // 默认加载推荐数据

        // 注册广播接收器
        updateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.example.qu_tao.UPDATE_POSTS".equals(intent.getAction())) {
                    loadRecommendData();
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.example.qu_tao.UPDATE_POSTS");
        ContextCompat.registerReceiver(requireContext(), updateReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 注销广播接收器
        requireContext().unregisterReceiver(updateReceiver);
    }

    private void initViews(View view) {
        tabFollow = view.findViewById(R.id.tab_follow);
        tabRecommend = view.findViewById(R.id.tab_recommend);
        recyclerView = view.findViewById(R.id.recyclerView);
        fab = view.findViewById(R.id.fab);
        tabMine = view.findViewById(R.id.tab_mine);
    }

    //悬浮窗(添加按钮）
    private void setupFab() {
        fab.setOnClickListener(v -> showPostDialog());
    }

    private void showPostDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(requireContext());
        View dialogView = LayoutInflater.from(requireContext())
                .inflate(R.layout.qutaoquan_dialog, null);
        dialog.setContentView(dialogView);

        // 写文章选项点击
        dialogView.findViewById(R.id.option_write_article).setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(getActivity(), XieWenZhangActivity.class));
        });

        // 发动态选项点击
        dialogView.findViewById(R.id.option_post_image).setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(getActivity(), FaDongTaiActivity.class));
        });

        // 取消按钮点击
        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    //关注、推荐标签切换
    private void setupTabs() {
        // 设置默认选中"推荐"标签
        selectTab(tabRecommend);

        tabFollow.setOnClickListener(v -> {
            selectTab(tabFollow);
            loadFollowData();
        });

        tabRecommend.setOnClickListener(v -> {
            selectTab(tabRecommend);
            loadRecommendData();
        });

        tabMine.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WodeQutaoquanActivity.class);
            startActivity(intent);
        });
    }

    private void selectTab(TextView selectedTab) {
        // 重置所有标签样式
        resetTabStyle(tabFollow);
        resetTabStyle(tabRecommend);

        // 设置选中标签样式
        if (selectedTab == tabFollow) {
            setSelectedTabStyle(tabFollow);
            setUnselectedTabStyle(tabRecommend);
        } else {
            setSelectedTabStyle(tabRecommend);
            setUnselectedTabStyle(tabFollow);
        }
    }

    private void setSelectedTabStyle(TextView tab) {
        tab.setTextColor(ContextCompat.getColor(requireContext(), COLOR_SELECTED));
        tab.setTextSize(TEXT_SIZE_SELECTED);
        tab.setTypeface(null, Typeface.BOLD);
    }

    private void setUnselectedTabStyle(TextView tab) {
        tab.setTextColor(ContextCompat.getColor(requireContext(), COLOR_UNSELECTED));
        tab.setTextSize(TEXT_SIZE_UNSELECTED);
        tab.setTypeface(null, Typeface.NORMAL);
    }

    private void resetTabStyle(TextView tab) {
        tab.setTextColor(ContextCompat.getColor(requireContext(), COLOR_UNSELECTED));
        tab.setTextSize(TEXT_SIZE_UNSELECTED);
        tab.setTypeface(null, Typeface.NORMAL);
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        postAdapter = new PostAdapter(getContext(), postList);
        recyclerView.setAdapter(postAdapter);

        postAdapter.setOnItemClickListener(new PostAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Post post) {
                // 处理帖子点击事件
            }

            @Override
            public void onLikeClick(Post post) {
                // 处理点赞点击事件
            }

            @Override
            public void onFollowClick(Post post, TextView followButton) {
                // 处理关注点击事件
                new Thread(() -> {
                    DBHelper dbHelper = new DBHelper(getContext());
                    SQLiteDatabase db = dbHelper.getReadableDatabase();

                    // 检查是否已经关注
                    String query = "SELECT * FROM follow WHERE user_id = ? AND followed_user_id = ?";
                    Cursor cursor = db.rawQuery(query, new String[]{"1", String.valueOf(post.getUserId())});

                    if (cursor.getCount() == 0) {
                        // 未关注，执行插入操作
                        SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.put("user_id", 1); // 假设当前用户 ID 为 1
                        values.put("followed_user_id", post.getUserId());

                        writableDb.insert("follow", null, values);
                        writableDb.close();
                    } else {
                        // 已关注，执行删除操作
                        SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
                        String whereClause = "user_id = ? AND followed_user_id = ?";
                        String[] whereArgs = new String[]{"1", String.valueOf(post.getUserId())};
                        writableDb.delete("follow", whereClause, whereArgs);
                        writableDb.close();
                    }

                    cursor.close();
                    db.close();

                    // 更新UI
                    getActivity().runOnUiThread(() -> {
                        if (isFollowed(post.getUserId())) {
                            followButton.setText("你关注的");
                        } else {
                            followButton.setText("关注");
                        }
                        // 刷新关注列表
                        if (tabFollow.getCurrentTextColor() == ContextCompat.getColor(requireContext(), COLOR_SELECTED)) {
                            loadFollowData();
                        }
                    });
                }).start();
            }

            private boolean isFollowed(int userId) {
                DBHelper dbHelper = new DBHelper(getContext());
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                String query = "SELECT * FROM follow WHERE user_id = ? AND followed_user_id = ?";
                Cursor cursor = db.rawQuery(query, new String[]{"1", String.valueOf(userId)});
                boolean isFollowed = cursor.getCount() > 0;
                cursor.close();
                db.close();
                return isFollowed;
            }
        });
    }

    @SuppressLint("Range")
    private void loadFollowData() {
        new Thread(() -> {
            DBHelper dbHelper = new DBHelper(getContext());
            SQLiteDatabase db = dbHelper.getReadableDatabase();

            List<Post> loadedPosts = new ArrayList<>();

            String query = "SELECT posts.post_id, posts.user_id, user.user_name, posts.content, posts.post_type, posts.create_time " +
                    "FROM posts " +
                    "JOIN user ON posts.user_id = user._id " +
                    "JOIN follow ON posts.user_id = follow.followed_user_id " +
                    "WHERE follow.user_id = ? " +
                    "ORDER BY posts.create_time DESC";

            Cursor postCursor = db.rawQuery(query, new String[]{"1"});

            if (postCursor != null && postCursor.getCount() > 0) {
                while (postCursor.moveToNext()) {
                    Post post = new Post();
                    post.setPostId(postCursor.getInt(postCursor.getColumnIndex("post_id")));
                    post.setUserId(postCursor.getInt(postCursor.getColumnIndex("user_id")));
                    post.setUsername(postCursor.getString(postCursor.getColumnIndex("user_name")));
                    post.setContent(postCursor.getString(postCursor.getColumnIndex("content")));
                    post.setPostType(postCursor.getInt(postCursor.getColumnIndex("post_type")));
                    post.setCreateTime(postCursor.getString(postCursor.getColumnIndex("create_time")));

                    // 查询关联的图片
                    List<byte[]> images = new ArrayList<>();
                    Cursor photoCursor = db.query("photo",
                            new String[]{"image"},
                            "post_id = ?",
                            new String[]{String.valueOf(post.getPostId())},
                            null, null, null);

                    if (photoCursor != null && photoCursor.moveToFirst()) {
                        do {
                            byte[] imageData = photoCursor.getBlob(photoCursor.getColumnIndex("image"));
                            if (imageData != null) {
                                images.add(imageData);
                            }
                        } while (photoCursor.moveToNext());
                        photoCursor.close();
                    }

                    post.setImages(images);
                    loadedPosts.add(post);
                }
                postCursor.close();
            }

            db.close();
            getActivity().runOnUiThread(() -> {
                postList.clear();
                postList.addAll(loadedPosts);
                postAdapter.notifyDataSetChanged();
            });
        }).start();
    }

    @SuppressLint("Range")
    private void loadRecommendData() {
        new Thread(() -> {
            DBHelper dbHelper = new DBHelper(getContext());
            SQLiteDatabase db = dbHelper.getReadableDatabase();

            List<Post> loadedPosts = new ArrayList<>();

            String query = "SELECT posts.post_id, posts.user_id, user.user_name, posts.content, posts.post_type, posts.create_time " +
                    "FROM posts " +
                    "JOIN user ON posts.user_id = user._id " +
                    "ORDER BY posts.create_time DESC";

            Cursor postCursor = db.rawQuery(query, null);

            if (postCursor != null && postCursor.getCount() > 0) {
                while (postCursor.moveToNext()) {
                    Post post = new Post();
                    post.setPostId(postCursor.getInt(postCursor.getColumnIndex("post_id")));
                    post.setUserId(postCursor.getInt(postCursor.getColumnIndex("user_id")));
                    post.setUsername(postCursor.getString(postCursor.getColumnIndex("user_name")));
                    post.setContent(postCursor.getString(postCursor.getColumnIndex("content")));
                    post.setPostType(postCursor.getInt(postCursor.getColumnIndex("post_type")));
                    post.setCreateTime(postCursor.getString(postCursor.getColumnIndex("create_time")));

                    // 查询关联的图片
                    List<byte[]> images = new ArrayList<>();
                    Cursor photoCursor = db.query("photo",
                            new String[]{"image"},
                            "post_id = ?",
                            new String[]{String.valueOf(post.getPostId())},
                            null, null, null);

                    if (photoCursor != null && photoCursor.moveToFirst()) {
                        do {
                            byte[] imageData = photoCursor.getBlob(photoCursor.getColumnIndex("image"));
                            if (imageData != null) {
                                images.add(imageData);
                            }
                        } while (photoCursor.moveToNext());
                        photoCursor.close();
                    }

                    post.setImages(images);
                    loadedPosts.add(post);
                }
                postCursor.close();
            }

            db.close();
            getActivity().runOnUiThread(() -> {
                postList.clear();
                postList.addAll(loadedPosts);
                postAdapter.notifyDataSetChanged();
            });
        }).start();
    }
}